package com.swak.utils.ssl;

import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLException;

import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;

/**
 * 借助 netty 的Ssl的创建方式
 * 
 * @author lifeng
 * @date 2021年2月24日 下午4:12:40
 */
public class SslContexts {

	private SslContextBuilder Builder;

	private SslContexts() {
		Builder = SslContextBuilder.forClient();

	}

	public SslContexts useKeyStore(KeyStore keystore, char[] keyPassword) {
		try {
			final KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			kmfactory.init(keystore, keyPassword);
			Builder.keyManager(kmfactory);
			return this;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public SslContext build() throws SSLException {
		return Builder.build();
	}

	public static SslContexts forClient() {
		return new SslContexts();
	}
}
